<template>
	<view class="chatInterface">
		<view class="scroll-view" @click="messageInputFocusin">
			<view class="all-history-loaded">{{ allHistoryLoaded ? '已经没有更多的历史消息' : '下拉获取历史消息' }}</view>
			<!--已经收到的消息-->
			<view v-for="(message, index) in messages" :key="message.messageId">
				<!--时间显示，类似于微信，隔5分钟不发言，才显示时间-->
				<view class="time-lag">{{ renderMessageDate(message, index) }}</view>
				<view class="message-item" :class="{ self: message.senderId == (currentUser && currentUser.uuid) }">
					<view class="avatar" v-if="message.senderId != (currentUser && currentUser.uuid)">
						<image :src="friend.avatar" @click="userClick"></image></view>
					<view class="avatar" v-else><image :src="currentUser.avatar"></image></view>
					<view class="content">
						<b class="pending" v-if="message.status == 'sending'"></b>
						<b class="send-fail" v-if="message.status == 'fail'"></b>
						<view v-if="message.type == 'text'" v-html="renderTextMessage(message)"></view>
						<image
							class="image-content"
							v-if="message.type == 'image'"
							:src="message.payload.url"
							:data-url="message.payload.url"
							@click="showImageFullScreen"
							mode="widthFix"
						></image>
						<view class="video-snapshot" v-if="message.type == 'video'" :data-url="message.payload.video.url" @click="playVideo">
							<image :src="message.payload.thumbnail.url" mode="aspectFit"></image>
							<view class="video-play-icon"></view>
						</view>
						<GoEasyAudioPlayer v-if="message.type == 'audio'" :src="message.payload.url" :duration="message.payload.duration" />
						<view class="custom-message" v-if="message.type == 'order'">
							<view class="title">
								<image src="../../../static/images/dingdan.png"></image>
								<text>自定义消息</text>
							</view>
							<view class="custom-message-item">编号：{{ message.payload.number }}</view>
							<view class="custom-message-item">商品: {{ message.payload.goods }}</view>
							<view class="custom-message-item">金额: {{ message.payload.price }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="action-box" v-if="!video.visible">
			<view class="action-top">
				<view class="message-input" style="margin-left: 30rpx;">
					<input type="text" maxlength="700" placeholder="发送消息" v-model="content" @focus="messageInputFocusin" />
				</view>
				<view style="width: 80rpx;height: 80rpx;display: flex;align-items: center;justify-content: center;" @click="showEmoji">
					<image src="../../../static/images/bqb.png" style="width: 50rpx;height: 50rpx;" mode=""></image>
				</view>
				<view style="width: 80rpx;height: 80rpx;display: flex;align-items: center;justify-content: center;" @click="showMore">
					<image src="../../../static/images/more.png" style="width: 50rpx;height: 50rpx;" mode=""></image>
				</view>
				<!-- <view class="file-icon emoji-icon" style="margin-left: 15rpx;" @click="showEmoji"></view>
				<view class="file-icon more-icon" style="margin-left: -10rpx;" @click="showMore"></view> -->
				<span class="send-message-btn" style="margin-left: 15rpx;color: #333333;" @click="sendTextMessage">发送</span>
			</view> 
			<!--展示表情列表-->
			<view class="action-bottom" v-if="emoji.show" style="flex-direction: row;flex-wrap: wrap;width: 100%;overflow-y: scroll;height: 360rpx">
				<image class="emoji-item" style="padding: 10rpx;" v-for="(emojiItem, emojiKey, index) in emoji.map" :key="index" :src="emoji.url + emojiItem" @click="selectEmoji(emojiKey)"></image>
			</view>
			<!--更多-->
			<view class="action-bottom" v-if="more.show">
				<view class="more-item" @click="sendImage">
					<image src="../../../static/images/sctp.png"></image>
					<text>图片</text>
				</view>
				<view class="more-item" @click="sendVideo">
					<image src="../../../static/images/xzsp.png"></image>
					<text>视频</text>
				</view> 
				<!-- <view class="more-item" @click="showCustomMessageForm">
					<image src="../../../static/images/zidingyi.png"></image>
					<text>自定义消息</text>
				</view> -->
			</view>
		</view>
		<view class="record-loading" v-if="audio.recording"></view>
		<video v-if="video.visible" :src="video.url" id="videoPlayer" @fullscreenchange="onVideoFullScreenChange"></video>
	</view>
</template>

<script>
import GoEasyAudioPlayer from '../../../components/GoEasyAudioPlayer/GoEasyAudioPlayer';
import EmojiDecoder from '../../../lib/EmojiDecoder';
const recorderManager = uni.getRecorderManager();

export default {
	name: 'privateChat',
	components: {
		GoEasyAudioPlayer
	},
	data() {
		let emojiUrl = 'https://imgcache.qq.com/open/qcloud/tim/assets/emoji/';
		let emojiMap = {
			'[嘘]': 'emoji_27@2x.png',
			'[困]': 'emoji_29@2x.png',
			'[坏笑]': 'emoji_30@2x.png',
			'[大哭]': 'emoji_33@2x.png',
			'[奋斗]': 'emoji_35@2x.png',
			'[委屈]': 'emoji_37@2x.png',
			'[害羞]': 'emoji_38@2x.png',
			'[尴尬]': 'emoji_39@2x.png',
			'[调皮]': 'emoji_113@2x.png',
			'[左哼哼]': 'emoji_40@2x.png',
			'[得意]': 'emoji_48@2x.png',
			'[微笑]': 'emoji_49@2x.png',
			'[心碎了]': 'emoji_50@2x.png',
			'[快哭了]': 'emoji_51@2x.png',
			'[怒]': 'emoji_53@2x.png',
			'[惊恐]': 'emoji_54@2x.png',
			'[憨笑]': 'emoji_56@2x.png',
			'[打哈欠]': 'emoji_58@2x.png',
			'[抓狂]': 'emoji_59@2x.png',
			'[折磨]': 'emoji_60@2x.png',
			'[抠鼻]': 'emoji_61@2x.png',
			'[抱抱]': 'emoji_62@2x.png',
			'[撇嘴]': 'emoji_67@2x.png',
			'[擦汗]': 'emoji_68@2x.png',
			'[敲打]': 'emoji_69@2x.png',
			'[晕]': 'emoji_70@2x.png',
			'[流汗]': 'emoji_75@2x.png',
			'[流泪]': 'emoji_76@2x.png',
			'[疑问]': 'emoji_90@2x.png',
			'[白眼]': 'emoji_91@2x.png',
			'[睡觉]': 'emoji_93@2x.png',
			'[糗大了]': 'emoji_100@2x.png',
			'[色]': 'emoji_105@2x.png',
			'[衰]': 'emoji_111@2x.png',
			'[鄙视]': 'emoji_119@2x.png',
			'[酷]': 'emoji_120@2x.png',
			'[闭嘴]': 'emoji_124@2x.png',
			'[阴险]': 'emoji_126@2x.png',
			'[难过]': 'emoji_127@2x.png',
			'[饥饿]': 'emoji_135@2x.png',
			'[鼓掌]': 'emoji_140@2x.png',
			'[龇牙]': 'emoji_141@2x.png',
			'[么么哒]': 'emoji_3@2x.png',
			'[偷笑]': 'emoji_7@2x.png',
			'[傲慢]': 'emoji_8@2x.png',
			'[再见]': 'emoji_9@2x.png',
			'[冷汗]': 'emoji_10@2x.png',
			'[发呆]': 'emoji_15@2x.png',
			'[可怜]': 'emoji_17@2x.png',
			'[可爱]': 'emoji_18@2x.png',
			'[右哼哼]': 'emoji_19@2x.png',
			'[大兵]': 'emoji_32@2x.png',
			'[惊讶]': 'emoji_55@2x.png',
			'[吐]': 'emoji_22@2x.png',
			'[吓]': 'emoji_23@2x.png',
			'[咒骂]': 'emoji_24@2x.png',
			'[便便]': 'emoji_5@2x.png',
			'[抱拳]': 'emoji_63@2x.png',
			'[拳头]': 'emoji_64@2x.png',
			'[爆筋]': 'emoji_81@2x.png',
			'[爱你]': 'emoji_82@2x.png',
			'[爱心]': 'emoji_83@2x.png',
			'[胜利]': 'emoji_104@2x.png',
			'[勾引]': 'emoji_14@2x.png',
			'[凋谢]': 'emoji_11@2x.png',
			'[刀]': 'emoji_12@2x.png',
			'[咖啡]': 'emoji_25@2x.png',
			'[啤酒]': 'emoji_26@2x.png',
			'[多云]': 'emoji_31@2x.png',
			'[太阳]': 'emoji_34@2x.png',
			'[奶瓶]': 'emoji_36@2x.png',
			'[左车头]': 'emoji_42@2x.png',
			'[弱]': 'emoji_44@2x.png',
			'[强]': 'emoji_45@2x.png',
			'[彩带]': 'emoji_46@2x.png',
			'[彩球]': 'emoji_47@2x.png',
			'[手枪]': 'emoji_57@2x.png',
			'[握手]': 'emoji_66@2x.png',
			'[月亮]': 'emoji_71@2x.png',
			'[棒棒糖]': 'emoji_72@2x.png',
			'[汽车]': 'emoji_73@2x.png',
			'[沙发]': 'emoji_74@2x.png',
			'[灯泡]': 'emoji_78@2x.png',
			'[炸弹]': 'emoji_79@2x.png',
			'[熊猫]': 'emoji_80@2x.png',
			'[猪头]': 'emoji_85@2x.png',
			'[猫咪]': 'emoji_86@2x.png',
			'[玫瑰]': 'emoji_88@2x.png',
			'[瓢虫]': 'emoji_89@2x.png',
			'[皮球]': 'emoji_92@2x.png',
			'[礼品袋]': 'emoji_96@2x.png',
			'[礼物]': 'emoji_97@2x.png',
			'[篮球]': 'emoji_98@2x.png',
			'[米饭]': 'emoji_99@2x.png',
			'[红双喜]': 'emoji_101@2x.png',
			'[红灯笼]': 'emoji_102@2x.png',
			'[纸巾]': 'emoji_103@2x.png',
			'[药]': 'emoji_106@2x.png',
			'[菜刀]': 'emoji_107@2x.png',
			'[蛋糕]': 'emoji_108@2x.png',
			'[蜡烛]': 'emoji_109@2x.png',
			'[西瓜]': 'emoji_112@2x.png',
			'[象棋]': 'emoji_114@2x.png',
			'[车厢]': 'emoji_117@2x.png',
			'[钞票]': 'emoji_121@2x.png',
			'[钻戒]': 'emoji_122@2x.png',
			'[闪电]': 'emoji_123@2x.png',
			'[闹钟]': 'emoji_125@2x.png',
			'[雨伞]': 'emoji_128@2x.png',
			'[青蛙]': 'emoji_129@2x.png',
			'[面条]': 'emoji_130@2x.png',
			'[鞭炮]': 'emoji_131@2x.png',
			'[风车]': 'emoji_132@2x.png',
			'[飞机]': 'emoji_134@2x.png',
			'[香蕉]': 'emoji_136@2x.png',
			'[骷髅]': 'emoji_137@2x.png',
			'[麦克风]': 'emoji_138@2x.png',
			'[麻将]': 'emoji_139@2x.png',
		};
		return {
			//聊天文本框
			content: '',
			objUuid: undefined,
			friend: null,
			currentUser: null,
			//已经接收到的消息
			messages: [],
			//已经加载完所有历史消息
			allHistoryLoaded: false,

			//定义表情列表
			emoji: {
				url: emojiUrl,
				map: emojiMap,
				show: false,
				decoder: new EmojiDecoder(emojiUrl, emojiMap)
			},
			more: {
				//更多按钮
				show: false
			},
			audio: {
				//语音录音中
				recording: false,
				//录音按钮展示
				visible: false
			},
			video: {
				visible: false,
				url: '',
				context: null
			}
		};
	},
	onReady() {
		this.video.context = uni.createVideoContext('videoPlayer', this);
	},
	onShow() {
		this.more.show = false;
		this.emoji.show = false;
	},
	onLoad(options) {
		// this.getUserData()
		let imService = getApp().globalData.imService;
		this.currentUser = uni.getStorageSync('currentUser');
		//聊天对象
		let friendId = options.to;
		this.objUuid = options.to
		//从服务器获取最新的好友信息
		this.friend = this.findFriendByIds(friendId);
		this.messages = imService.getPrivateMessages(friendId);
		uni.setNavigationBarTitle({
			title: this.friend.name
		});
		//监听新消息
		imService.onNewPrivateMessageReceive = (friendId, message) => {
			if (friendId === this.friend.uuid) {
				//聊天时，收到消息标记为已读
				this.markPrivateMessageAsRead(friendId);
				//收到新消息，是滚动到最底部
				this.scrollToBottom();
			}
		};
		//每次进入聊天页面，总是滚动到底部
		this.scrollToBottom();
		// 录音监听器
		// this.initRecorderListeners();
		//收到的消息设置为已读
		if (this.messages.length !== 0) {
			this.markPrivateMessageAsRead(friendId);
		}
	},
	onPullDownRefresh(e) {
		this.loadMoreHistoryMessage();
	},
	onUnload() {
		//退出聊天页面之前，清空页面传入的监听器
		let imService = getApp().globalData.imService;
		if (imService) {
			imService.onNewPrivateMessageReceive = (friendId, message) => {};
		}
	},
	methods: {
		userClick () {
			let uid = uni.getStorageSync('objUuid')
			if(this.objUuid){
				uni.navigateTo({
					url: '../../../myPackageA/user/components/profile?uid=' + this.objUuid
				})
			}else{
				uni.navigateTo({
					url: '../../../myPackageA/user/components/profile?uid=' + uid
				})
			}
		},
		findUserByIds(userId) {
			let data = uni.getStorageSync('masterList')
			let dataLists = JSON.parse(data)
		    let user = dataLists.find(user => (user.uuid == userId))
		    return user;
		},
		Friends(uuid, name, avatar) {
		    return {
				uuid: uuid,
				name: name,
				avatar: avatar
			}
		},
		findFriendByIds(userId) {
		    let user = this.findUserByIds(userId);
		    return this.Friends(user.uuid, user.name, user.avatar);
		},
		toServer(){
			let self = this;//连接服务
			let userData = {
				id:	uni.getStorageSync('uid'),
				data: {"avatar":uni.getStorageSync('userData').avatar,"nickname":uni.getStorageSync('userData').nickname}
			}
			uni.setStorageSync('userImg',userData.data.avatar)
			self.goeasys.connect({
				id: userData.id, 		//pubsub选填，im必填
				data: userData.data, 		//必须是一个对象，pubsub选填，im必填，用于上下线提醒和查询在线用户列表时，扩展更多的属性
				onSuccess: function () {  //连接成功
					console.log("GoEasy connect successfully.1") //连接成功
					// var im = self.goeasys.im;
					// im.latestConversations({
					// 	onSuccess: function (result) {
					// 		console.log(3333)
					// 		console.log(result)
					// 		console.log(3333)
					// 	},
					// 	onFailed: function (error) { //获取失败
					// 		console.log("Failed to get the latest conversations, code:" + error.code + " content:" + error.content);
					// 	},
					// })
					// self.goeasys.im.on(self.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, (content) => {
					// 	console.log(11111111)
					// 	console.log(content)
					// 	self.renderConversations(content);
					// });
					//加载会话列表
					// this.goeasys.im.latestConversations({
					// 	onSuccess: function (result) {
					// 		console.log(result)
					// 		console.log(222222222222)
					// 		let content = result.content;
					// 		this.renderConversations(content);
					// 		uni.hideLoading();
					// 	},
					// 	onFailed: function (error) {
					// 		console.log(error)
					// 		//获取失败
					// 		uni.hideLoading()
					// 		console.log("失败获取最新会话列表, code:" + error.code + " content:" + error.content);
					// 	}
					// });
				},
				onFailed: function (error) { //连接失败
					console.log("Failed to connect GoEasy, code:"+error.code+ ",error:"+error.content);
				},
				onProgress:function(attempts) { //连接或自动重连中
					console.log("GoEasy is connecting", attempts);
				}
			});
			self.getUserData()
		},
		//渲染文本消息，如果包含表情，替换为图片
		//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
		renderTextMessage(message) {
			return '<span class="text-content">' + this.emoji.decoder.decode(message.payload.text) + '</span>';
		},
		//像微信那样显示时间，如果有几分钟没发消息了，才显示时间
		//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
		renderMessageDate(message, index) {
			if (index === 0) {
				return this.formatDate(message.timestamp);
			} else {
				if (message.timestamp - this.messages[index - 1].timestamp > 5 * 60 * 1000) {
					return this.formatDate(message.timestamp);
				}
			}
			return '';
		},
		sendMessage(message) {
			let toId = message.to.id;
			let imService = getApp().globalData.imService;
			let localHistory = imService.getPrivateMessages(toId);
			localHistory.push(message);
			this.goEasy.im.sendMessage({
				message: message,
				onSuccess: function(message) {
					console.log('发送成功.', message);
				},
				onFailed: function(error) {
					console.log('发送失败:', error);
				}
			});
		},
		sendTextMessage() {
			//发送消息
			if (this.content.trim() !== '') {
				let body = this.content;
				if (this.content.length >= 50) {
					body = this.content.substring(0, 30) + '...';
				}
				let textMessage = this.goEasy.im.createTextMessage({
					text: this.content,
					to: {
						id: this.friend.uuid,
						type: this.GoEasy.IM_SCENE.PRIVATE,
						data: {
							name: this.friend.name,
							avatar: this.friend.avatar
						}
					},
					notification: {
						title: this.currentUser.name + '发来一段文字',
						body: body // 字段最长 50 字符
					}
				});
				this.sendMessage(textMessage);
			}
			this.scrollToBottom();
			this.content = '';
		},
		loadMoreHistoryMessage() {
			//历史消息
			let self = this;
			let lastMessageTimeStamp = Date.now();
			let lastMessage = this.messages[0];
			if (lastMessage) {
				lastMessageTimeStamp = lastMessage.timestamp;
			}
			let currentLength = this.messages.length;
			this.goEasy.im.history({
				userId: self.friend.uuid,
				lastTimestamp: lastMessageTimeStamp,
				onSuccess: function(result) {
					//获取本地记录
					let imService = getApp().globalData.imService;
					let localHistory = imService.getPrivateMessages(self.friend.uuid);
					//添加加载的记录到本地记录尾部
					let messages = result.content;
					for (let i = messages.length - 1; i >= 0; i--) {
						localHistory.unshift(messages[i]);
					}
					if (localHistory.length === currentLength) {
						self.allHistoryLoaded = true;
					}
					self.messages = localHistory;
					uni.stopPullDownRefresh();
				},
				onFailed: function(error) {
					//获取失败
					if (error.code === 401) {
						console.log('获取历史消息失败,默认不开通，付费应用，可以在我的应用->查看详情，高级功能里自助开通');
					} else {
						console.log('获取历史消息失败, code:' + error.code + ',错误信息:' + error.content);
					}
					uni.stopPullDownRefresh();
				}
			});
		},
		//语音录制按钮和键盘输入的切换
		switchAudioKeyboard() {
			this.audio.visible = !this.audio.visible;
			if (uni.authorize) {
				uni.authorize({
					scope: 'scope.record'
				});
			}
		},
		onRecordStart() {
			try {
				recorderManager.start();
			} catch (e) {
				uni.showModal({
					title: '录音错误',
					content: '请在app和小程序端体验录音，Uni官方明确H5不支持getRecorderManager, 详情查看Uni官方文档'
				});
			}
		},
		onRecordEnd() {
			try {
				recorderManager.stop();
			} catch (e) {
				console.log(e);
			}
		},
		sendVideo() {
			//发送文件
			uni.chooseVideo({
				success: res => {
					let videoMessage = this.goEasy.im.createVideoMessage({
						to: {
							id: this.friend.uuid,
							type: this.GoEasy.IM_SCENE.PRIVATE,
							data: {
								name: this.friend.name,
								avatar: this.friend.avatar
							}
						},
						file: res,
						onProgress: function(progress) {
							console.log(progress);
						},
						notification: {
							title: this.currentUser.name + '发来一个视频',
							body: '[视频消息]' // 字段最长 50 字符
						}
					});
					this.sendMessage(videoMessage);
				}
			});
		},
		sendImage() {
			uni.chooseImage({
				count: 1,
				success: res => {
					let imageMessage = this.goEasy.im.createImageMessage({
						to: {
							id: this.friend.uuid,
							type: this.GoEasy.IM_SCENE.PRIVATE,
							data: {
								name: this.friend.name,
								avatar: this.friend.avatar
							}
						},
						file: res,
						onProgress: function(progress) {
							console.log(progress);
						},
						notification: {
							title: this.currentUser.name + '发来一张图片',
							body: '[图片消息]' // 字段最长 50 字符
						}
					});
					this.sendMessage(imageMessage);
				}
			});
		},
		showImageFullScreen(e) {
			var imagesUrl = [e.currentTarget.dataset.url];
			uni.previewImage({
				urls: imagesUrl
			});
		},
		playVideo(e) {
			this.video.visible = true;
			this.video.url = e.currentTarget.dataset.url;
			this.$nextTick(() => {
				this.video.context.requestFullScreen({
					direction: 0
				});
				this.video.context.play();
			});
		},
		onVideoFullScreenChange(e) {
			//当退出全屏播放时，隐藏播放器
			if (this.video.visible && !e.detail.fullScreen) {
				this.video.visible = false;
				this.video.context.stop();
			}
		},
		messageInputFocusin() {
			this.more.show = false;
			this.emoji.show = false;
		},
		showEmoji() {
			this.emoji.show = !this.emoji.show;
			this.more.show = false;
		},
		showMore() {
			this.more.show = !this.more.show;
			this.emoji.show = false;
		},
		selectEmoji(emojiKey) {
			this.content += emojiKey;
			// this.sendTextMessage()
		},
		showCustomMessageForm() {
			let to = {
				id: this.friend.uuid,
				name: this.friend.name,
				avatar: this.friend.avatar,
				type: this.GoEasy.IM_SCENE.PRIVATE
			};
			uni.navigateTo({
				url: '../customMessage/customMessage?to=' + JSON.stringify(to)
			});
		},
		scrollToBottom() {
			this.$nextTick(function() {
				uni.pageScrollTo({
					scrollTop: 2000000,
					duration: 10
				});
			});
		},
		markPrivateMessageAsRead(friendId) {
			this.goEasy.im.markPrivateMessageAsRead({
				userId: friendId,
				onSuccess: function() {
					console.log('标记为已读成功');
				},
				onFailed: function(error) {
					console.log(error);
				}
			});
		}
	}
};
</script>

<style scoped>
view,
text {
	box-sizing: content-box !important;
}
image{
	border-radius: 50rpx;
}
</style>
